(async function () {        
    // DOM元素
    const todayDateEl = document.getElementById('todayDate');
    const calendarGrid = document.getElementById('calendarGrid');
    const currentMonthEl = document.getElementById('currentMonth');
    const prevMonthBtn = document.getElementById('prevMonth');
    const nextMonthBtn = document.getElementById('nextMonth');
    const todayBtn = document.getElementById('todayDate');
    const eventModal = document.getElementById('eventModal');
    const modalTitle = document.getElementById('modalTitle');
    const eventTitle = document.getElementById('eventTitle');
    const startDate = document.getElementById('startDate');
    const endDate = document.getElementById('endDate');
    const saveEventBtn = document.getElementById('saveEvent');
    const eventList = document.getElementById('eventList');

    // 当前日期和显示的月份
    const today = new Date();
    let currentDate = new Date();
    let events = []; // 存储所有事件 { id, title, start, end }
    let selectedDate = null;
    let dayElements = []; // 存储所有日期元素及其信息

    // 初始化
    await init();
    const boardLabel = 'calendarNotes';
    const boardNote = await api.runOnBackend((aa) => {
        const notes = api.getNotesWithLabel(aa)[0];
        return notes;
    },[boardLabel]);
    
    async function init() {
           // 设置当天日期显示
        todayDateEl.textContent = `今天 ${formatDate(today)}`;
        renderCalendar();
        setupEventListeners();
    }

        function setupEventListeners() {
            prevMonthBtn.addEventListener('click', () => {
                currentDate.setMonth(currentDate.getMonth() - 1);
                renderCalendar();
            });

            nextMonthBtn.addEventListener('click', () => {
                currentDate.setMonth(currentDate.getMonth() + 1);
                renderCalendar();
            });

            todayBtn.addEventListener('click', () => {
                currentDate = new Date();
                renderCalendar();
            });

            saveEventBtn.addEventListener('click', saveEvent);

            // 点击模态框外部关闭
            eventModal.addEventListener('click', (e) => {
                if (e.target === eventModal) {
                    closeModal();
                }
            });
        }

        async function renderCalendar() {
            // 加载事件数据
            //const savedEvents1 = localStorage.getItem('calendarEvents');
            //console.log("1222",savedEvents1);        
            const savedEvents =await CalendarShow('calendarNotes');
            if (savedEvents) {
                events = JSON.parse(savedEvents).map(event => ({
                    ...event,
                    start: new Date(event.start),
                    end: new Date(event.end)
                }));
            }
            // 更新月份显示
            const year = currentDate.getFullYear();
            const month = currentDate.getMonth();
            currentMonthEl.textContent = `${year}年${month + 1}月`;

            // 清空日历
            calendarGrid.innerHTML = '';
            dayElements = [];

            // 获取月份信息
            const firstDay = new Date(year, month, 1);
            const lastDay = new Date(year, month + 1, 0);
            
            // 计算第一天是星期几 (0是星期日，转换为1-7，1是星期一)
            let firstDayOfWeek = firstDay.getDay() || 7;
            firstDayOfWeek--; // 转换为0-6，0是星期一

            // 添加上个月的尾巴
            const prevMonth = new Date(year, month, 0);
            const prevMonthDays = firstDayOfWeek;
            const prevMonthLastDate = prevMonth.getDate();

            for (let i = 0; i < prevMonthDays; i++) {
                const date = new Date(year, month - 1, prevMonthLastDate - prevMonthDays + i + 1);
                const day = createDayElement(date, true);
                calendarGrid.appendChild(day);
            }

            // 添加当月的日期
            for (let i = 1; i <= lastDay.getDate(); i++) {
                const date = new Date(year, month, i);
                const day = createDayElement(date, false);
                calendarGrid.appendChild(day);
            }

            // 添加下个月的开头
            const totalDays = 42; // 6周 * 7天
            const daysToAdd = totalDays - (prevMonthDays + lastDay.getDate());
            
            for (let i = 1; i <= daysToAdd; i++) {
                const date = new Date(year, month + 1, i);
                const day = createDayElement(date, true);
                calendarGrid.appendChild(day);
            }

            // 渲染所有事件
                 
            // 加载本地存储的事件
            renderAllEvents();
        }

        function createDayElement(date, isOtherMonth) {
            const day = document.createElement('div');
            const dateStr = formatDateUTC(date);
			    date = new Date(+new Date(date) + 8 * 3600 * 1000);
            
            // 计算这一天属于日历中的第几行（0-5）和第几列（0-6）
            const dayIndex = dayElements.length;
            const row = Math.floor(dayIndex / 7);
            const col = dayIndex % 7;
            
            day.classList.add('day');
            if (isOtherMonth) day.classList.add('other-month');
            day.dataset.date = dateStr;
            day.dataset.row = row;
            day.dataset.col = col;
            
            // 标记今天
            const today = new Date();
            if (isSameDay(date, today)) {
                day.classList.add('today');
            }
            
            // 日期数字
            const dayNumber = document.createElement('div');
            dayNumber.classList.add('day-number');
            dayNumber.textContent = date.getDate()+'日';
            
            // 日期内容区域
            const dayContent = document.createElement('div');
            dayContent.classList.add('day-content');
            
            // 添加点击区域覆盖层，确保点击日期能打开弹窗
            const clickOverlay = document.createElement('div');
            clickOverlay.style.position = 'absolute';
            clickOverlay.style.top = '0';
            clickOverlay.style.left = '0';
            clickOverlay.style.width = '100%';
            clickOverlay.style.height = '100%';
            clickOverlay.style.zIndex = '4'; // 确保覆盖层在最上层
            clickOverlay.style.cursor = 'pointer';
            clickOverlay.addEventListener('click', () => {
                openModal(date);
            });
            
            // 如果是当天，添加特殊样式
            if (isSameDay(date, today)) {
                dayNumber.style.backgroundColor = '#3498db';
                dayNumber.style.color = 'white';
                dayNumber.style.padding = '2px 6px';
                dayNumber.style.borderRadius = '50%';
                dayNumber.style.marginBottom = '4px';
				day.classList.add('highlight-day');
            }
            day.appendChild(dayNumber);
            day.appendChild(dayContent);
            day.appendChild(clickOverlay); // 添加覆盖层
            
            // 存储日期元素及其信息
            dayElements.push({
                element: day,
                date: date,
                row: row,
                col: col,
                isOtherMonth: isOtherMonth
            });
            
            return day;
        }

        function renderAllEvents() {
            
            // 按日期分组事件并计算每日事件布局
            const dailyEventPositions = calculateDailyEventPositions();
            
            // 计算每天需要的高度并设置
            setDayHeights(dailyEventPositions);
            
            // 渲染单日事件
            dayElements.forEach(dayInfo => {
                const dayContent = dayInfo.element.querySelector('.day-content');
                const dateStr = formatDateUTC(dayInfo.date);
                
                // 获取当天的所有事件
                const dayEvents = dailyEventPositions.get(dateStr) || [];
                console.log(dateStr,dayEvents,dailyEventPositions);
                
                // 过滤出单日事件并按行渲染
                dayEvents.filter(event => isSameDay(new Date(event.event.start), new Date(event.event.end)))
                         .forEach(event => {
                             const eventEl = createEventElement(event.event, false);
                             eventEl.style.top = `${event.row * 22}px`; // 每行20px高度
							          //console.log(event,event.row,eventEl.style.top);
                             dayContent.appendChild(eventEl);
                         });
            });
            
            // 渲染多日事件
            events.filter(event => !isSameDay(new Date(event.start), new Date(event.end)))
                  .forEach(event => renderMultiDayEvent(event, dailyEventPositions));
			
        }

        // 根据事件数量设置日期框高度
        function setDayHeights(dailyEventPositions) {
            dayElements.forEach(dayInfo => {
                const dateStr = formatDateUTC(dayInfo.date);
                const dayEvents = dailyEventPositions.get(dateStr) || [];
                
                // 计算当天事件的最大行数
                const maxRow = dayEvents.length > 0 
                    ? Math.max(...dayEvents.map(e => e.row)) 
                    : 0;
                // 根据事件数量设置高度 (每行22px，加上顶部25px)
                const requiredHeight = 25 + (maxRow + 1) * 22;
                const minHeight = Math.max(100, requiredHeight); // 至少100px
                
                dayInfo.element.style.minHeight = `${minHeight}px`;
            });
        }

        // 计算每天的事件位置，确保同一天事件不重叠
        function calculateDailyEventPositions() {
            const dateGroups = new Map();
            const eventRowAssignments = new Map();
            // 跟踪跨天事件
            const allDayEvents = new Set();
    
            events.forEach(event => {
                const start = new Date(event.start);
                const end = new Date(event.end);
        
                // 判断是否为跨天事件
                const isAllDay = formatDateUTC(start) !== formatDateUTC(end);
                if (isAllDay) {
                    allDayEvents.add(event.id);
                 }
        
                // 按日期分组
                for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
                    const dateStr = formatDateUTC(d);
                    if (!dateGroups.has(dateStr)) {
                        dateGroups.set(dateStr, []);
                    }
                    dateGroups.get(dateStr).push(event);
                }
            });
    
            const dailyPositions = new Map();
    
            dateGroups.forEach((events, dateStr) => {
                const sortedEvents = [...events].sort((a, b) => new Date(a.start) - new Date(b.start));
        
                // 关键改进：全局跟踪当天已使用的所有行号，确保唯一性
                const usedRows = new Set();
                // 分离跟踪不同类型事件的行结束时间
                const allDayRowEndTimes = [];
                const singleDayRowEndTimes = [];
                const eventPositions = [];
        
                sortedEvents.forEach(event => {
                    const eventStart = new Date(event.start);
                    const eventEnd = new Date(event.end);
                    const isAllDay = allDayEvents.has(event.id);
                    let row, targetEndTimes;
            
                    // 区分跨天和单日事件的行号空间
                    if (isAllDay) {
                        targetEndTimes = allDayRowEndTimes;
                    } else {
                        targetEndTimes = singleDayRowEndTimes;
                    }
            
                    if (eventRowAssignments.has(event.id)) {
                        // 使用已分配的行号，但需确保在当前日期未被使用
                        row = eventRowAssignments.get(event.id);
                
                        // 核心检查：如果行号已被使用，找到下一个可用行号
                        while (usedRows.has(row)) {
                            row++;
                        }
                        // 更新事件的行号分配
                        eventRowAssignments.set(event.id, row);
                    } else {
                        // 新事件：在对应类型的行空间中寻找可用行
                        row = 0;
                        while (row < targetEndTimes.length) {
                            if (targetEndTimes[row] <= eventStart && !usedRows.has(row)) {
                                break;
                            }
                            row++;
                        }
                        // 如果找到的行号已被使用，继续寻找
                        while (usedRows.has(row)) {
                            row++;
                        }
                        eventRowAssignments.set(event.id, row);
                    }
            
                    // 标记此行号为已使用（关键：确保当天唯一性）
                    usedRows.add(row);
            
                    // 更新对应类型行空间的结束时间
                    if (row >= targetEndTimes.length) {
                        targetEndTimes.push(eventEnd);
                    } else {
                        targetEndTimes[row] = eventEnd;
                    }
            
                        eventPositions.push({ event, row, isAllDay });
                });
        
                dailyPositions.set(dateStr, eventPositions);
            });
    
            return dailyPositions;
        }
    
    

        // 将多日事件按周分割并渲染
        function renderMultiDayEvent(event, dailyEventPositions) {
            const start = new Date(event.start);
            const end = new Date(event.end);
            
            // 获取事件覆盖的所有日期元素
            const eventDays = dayElements.filter(dayInfo => {
			 
                return dayInfo.date >= start && dayInfo.date <= end;
            });
           
            if (eventDays.length === 0) return;
            
            // 按周分组事件日期
            const weekGroups = groupDaysByWeek(eventDays);
            //console.log(event,weekGroups);
            // 为每周的事件片段创建长条
            weekGroups.forEach((weekDays, weekIndex) => {
                // 获取这一组的第一个和最后一个日期
                const firstDay = weekDays[0];
				
                const lastDay = weekDays[weekDays.length - 1];
                
                // 获取事件在第一天的行号（决定垂直位置）
                const firstDayStr = formatDateUTC(firstDay.date);
                const firstDayEvents = dailyEventPositions.get(firstDayStr) || [];
                const eventPos = firstDayEvents.find(pos => pos.event.id === event.id);
                const row = eventPos ? eventPos.row : 0;
                
                // 创建事件元素
                const eventEl = createEventElement(event, true);
                
                // 设置样式
                if (weekGroups.length === 1) {
                    // 整个事件在同一周内
                    eventEl.classList.add('start', 'end');
                } else {
                    if (weekIndex === 0) {
                        eventEl.classList.add('start'); // 第一周的片段
                    } else if (weekIndex === weekGroups.length - 1) {
                        eventEl.classList.add('end'); // 最后一周的片段
                    } else {
                        eventEl.classList.add('middle'); // 中间周的片段
                    }
                }
                
                // 计算宽度和位置
                const firstDayRect = firstDay.element.getBoundingClientRect();
                const lastDayRect = lastDay.element.getBoundingClientRect();
                const calendarRect = calendarGrid.getBoundingClientRect();
				const daycontentRect = firstDay.element.querySelector('.day-content').getBoundingClientRect();
                
                // 计算垂直位置（基于行号）
                const verticalOffset = 25 + row * 22; // 25是避开日期数字的偏移量
                eventEl.style.top = `${firstDayRect.top - calendarRect.top + verticalOffset}px`;
                eventEl.style.left = `${firstDayRect.left - calendarRect.left + 4}px`;
                eventEl.style.width = `${lastDayRect.right - firstDayRect.left - 8}px`;
                //console.log(event,row,eventEl.style.top);
                // 添加到日历网格
                calendarGrid.appendChild(eventEl);
            });
        }

        // 将日期按周分组（每周从星期一开始）
        function groupDaysByWeek(days) {
            const weekGroups = [];
            if (days.length === 0) return weekGroups;
            
            // 按日期排序
            const sortedDays = [...days].sort((a, b) => a.date - b.date);
            
            let currentWeek = [sortedDays[0]];
            
            for (let i = 1; i < sortedDays.length; i++) {
                const prevDay = sortedDays[i - 1];
                const currentDay = sortedDays[i];
                
                // 检查是否是同一周（周一到周日）
                // 如果前一天是周日（6）而当前天是周一（0），则属于不同周
                if (prevDay.col === 6 && currentDay.col === 0) {
                    weekGroups.push(currentWeek);
                    currentWeek = [currentDay];
                } else {
                    currentWeek.push(currentDay);
                }
            }
            
            // 添加最后一组
            weekGroups.push(currentWeek);
            
            return weekGroups;
        }

        function createEventElement(event, isMultiDay) {
            const eventEl = document.createElement('div');
            eventEl.classList.add(isMultiDay ? 'multi-day-event' : 'event');
            eventEl.style.backgroundColor = getEventColor(event.id);
            eventEl.textContent = event.title;
            
            // 创建事件交互覆盖层，确保在顶层可以点击
            const overlay = document.createElement('div');
            overlay.classList.add('event-overlay');
            overlay.style.position = 'absolute';
            overlay.style.top = '0';
            overlay.style.left = '0';
            overlay.style.width = '100%';
            overlay.style.height = '100%';
            overlay.style.zIndex  = '90';
            overlay.addEventListener('click', (e) => {
                // 手动隐藏提示框
                tooltip.style.opacity = '0';
                tooltip.style.display = 'none';
                //document.removeEventListener('mousemove', handleMouseMove);
                e.stopPropagation(); // 阻止事件冒泡到日期点击
                showEventDetails(event);
            });
            // 创建悬浮提示框
            const tooltip = document.createElement('div');
            tooltip.classList.add('tooltip');
            tooltip.innerHTML = `
                <div class="tooltip-title">${event.title}</div>
                <div class="tooltip-time">开始: ${formatDate(event.start)}</div>
                <div class="tooltip-time">结束: ${formatDate(event.end)}</div>
            `;
            tooltip.style.display = 'none';
            document.body.appendChild(tooltip);
    
            // 鼠标移动处理函数 - 实时更新提示框位置
            /*const handleMouseMove = (e) => {
                // 定位在鼠标右侧10px处，垂直居中对齐鼠标
                tooltip.style.left = `${e.clientX + 10}px`;
                tooltip.style.top = `${e.clientY}px`;
            };*/
    
            // 鼠标进入时显示提示框
            eventEl.addEventListener('mouseenter', (e) => {
                //handleMouseMove(e); // 初始化位置
                // 定位在鼠标右侧10px处，垂直居中对齐鼠标
                tooltip.style.left = `${e.clientX + 10}px`;
                tooltip.style.top = `${e.clientY}px`;
                tooltip.style.display = 'block';
                // 延迟显示动画
                setTimeout(() => {
                    tooltip.style.opacity = '1';
                }, 10);
                // 监听鼠标移动，实时更新位置
                //document.addEventListener('mousemove', handleMouseMove);
            });
    
            // 鼠标离开时隐藏提示框
            eventEl.addEventListener('mouseleave', () => {
                tooltip.style.opacity = '0';
                // 延迟隐藏以等待动画完成
                setTimeout(() => {
                    tooltip.style.display = 'none';
                }, 200);
                // 移除鼠标移动监听
                //document.removeEventListener('mousemove', handleMouseMove);
            });
            
            eventEl.appendChild(overlay);
            return eventEl;
        }

        function openModal(date) {
            selectedDate = date;
            const dateStr =formatDateUTC(date);
            
            modalTitle.textContent = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
            
            // 设置默认日期
            startDate.value = dateStr;
            endDate.value = dateStr;
            eventTitle.value = '';
            
            // 显示当天的事件
            renderEventList(date);
            
            eventModal.style.display = 'flex';
        }

        function closeModal() {
            eventModal.style.display = 'none';
        }

        function renderEventList(date) {
            eventList.innerHTML = '';
            const dateStr = formatDateUTC(date);
            
            // 找出所有与该日期相关的事件
            const relatedEvents = events.filter(event => {
                const eventStart = new Date(event.start);
                const eventEnd = new Date(event.end);
                const eventDate = new Date(dateStr);
                return eventDate >= eventStart && eventDate <= eventEnd;
            });

            if (relatedEvents.length === 0) {
                eventList.innerHTML = '<p>没有事件</p>';
                return;
            }

            relatedEvents.forEach(event => {
                const eventItem = document.createElement('div');
                eventItem.classList.add('event-item');
                
                const eventText = document.createElement('span');
                eventText.textContent = event.title;
                eventText.style.backgroundColor = getEventColor(event.id);
                eventText.style.padding = '2px 5px';
                eventText.style.borderRadius = '2px';
                eventText.style.color = 'white';
                
                const deleteBtn = document.createElement('button');
                deleteBtn.classList.add('delete-btn');
                deleteBtn.textContent = '删除';
                deleteBtn.addEventListener('click', () => {
                    deleteEvent(event.id);
                });
                
                eventItem.appendChild(eventText);
                eventItem.appendChild(deleteBtn);
                eventList.appendChild(eventItem);
            });
        }

        function saveEvent() {
            const title = eventTitle.value.trim();
            const start = new Date(startDate.value);
            const end = new Date(endDate.value);

            if (!title || !start || !end || start > end) {
                alert('请输入有效的事件信息');
                return;
            }

            // 添加新事件
            //events.push({
            //    id: Date.now().toString(),
            //    title,
            //    start,
            //    end
            //});
            CalendarAdd(boardNote,title,formatDate(start),formatDate(end));
            // 保存到本地存储
            //saveEventsToLocalStorage();
            
            // 重新渲染
            renderCalendar();
            closeModal();
        }

        function deleteEvent(id) {
            CalendarDelete(id);
            //events = events.filter(event => event.id !== id);
            //saveEventsToLocalStorage();
            renderCalendar();
            renderEventList(selectedDate);
        }

        function showEventDetails(event) {
            // 全局隐藏所有提示框
            document.querySelectorAll('.tooltip').forEach(tooltip => {
                tooltip.style.opacity = '0';
                tooltip.style.display = 'none';
            });
            // 移除所有鼠标移动监听
            document.removeEventListener('mousemove', () => {});
            CalendarOpen(event.id);
            //alert(`事件: ${event.title}\n开始: ${formatDate(event.start)}\n结束: ${formatDate(event.end)}\n`);
        }

        function saveEventsToLocalStorage() {
            localStorage.setItem('calendarEvents', JSON.stringify(events));
        }

        // 工具函数
        function isSameDay(date1, date2) {
            return date1.getDate() === date2.getDate() &&
                   date1.getMonth() === date2.getMonth() &&
                   date1.getFullYear() === date2.getFullYear();
        }

        function formatDate(date) {
            return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
        }
		function formatDateUTC(dateTime) {
			const date = new Date(+new Date(dateTime) + 8 * 3600 * 1000); // 加8小时
			return date.toISOString().split('T')[0];
		}

        // 根据ID生成一致的颜色
        function getEventColor(id) {
            // 简单的哈希函数生成颜色
            let hash = 0;
            for (let i = 0; i < id.length; i++) {
                hash = id.charCodeAt(i) + ((hash << 5) - hash);
            }
            const color = `hsl(${(hash % 360 + 360) % 360}, 70%, 60%)`;
            return color;
        }

 })();